package com.sys.midware.assist.shell;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class RunShell {

    public static void execShell(String shell) {
        try {
            Process pro = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", shell});
            pro.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getExecResult(String shell) {
        BufferedReader bufferedReader = null;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            Process pro = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", shell});
            bufferedReader = new BufferedReader(new InputStreamReader(pro.getInputStream()), 1024);
            pro.waitFor();
            String line = null;
            while (bufferedReader != null && (line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }

    public static void execShell(String shell, String logPath) {
        BufferedReader bufferedReader = null;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            Process pro = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", shell});
            bufferedReader = new BufferedReader(new InputStreamReader(pro.getInputStream()), 1024);
            pro.waitFor();
            String line = null;
            while (bufferedReader != null && (line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line).append("\r\n");
            }
        } catch (Exception e) {
            stringBuffer.append(e.getMessage()).append("\r\n");
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                OutputStreamWriter outputStreamWriter = null;
                try {
                    bufferedReader.close();
                    // 将Shell的执行情况输出到日志文件中
                    OutputStream outputStream = new FileOutputStream(logPath);
                    outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
                    outputStreamWriter.write(stringBuffer.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        outputStreamWriter.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
